<?php
namespace app\index\controller;
use app\index\model\Common;
use app\index\model\Feedbacktag;
use app\index\model\Shareimg;
use app\index\model\WithdrawalRecord;
use think\Controller;
use think\facade\Request;
use think\facade\Validate;

class User extends Controller
{

	public function index()
	{

		$userId = input('param.user_id');
		if (empty($userId)) {
            $this->ajaxReturn(null, '参数错误,无用户参数', 201);
		}

		$user = db('user')->where('id', $userId)->find();
		if ($user) {
            $c = db('company')->where('user_id', $user['id'])->field('logo,id,status')->find();
            $h = db('bounty_hunter')->where('user_id', $user['id'])->field('id,status')->find();
            $user['status']  = $c?$c['status']:($h?$h['status']:0);
            $user['is_role'] = $c?3:($h?2:1);
            $user['logo'] = '';
            if ($c) {
                $user['logo'] =  $c['logo'];
            }
            $this->ajaxReturn($user, 'ok', 200);
        }else{
            $this->ajaxReturn(null, '数据为空', 200);
        }
	}




    /**
     * 用户修改资料
     */
    public function set()
    {
        $post = input('post.');
        $userId = $post['id'];

        if (empty($userId)) {
            $this->ajaxReturn(null, '参数错误', 201);
        }

        $user = db('user')->where('id', $userId)->field('id')->find();
        if (empty($user)) {
            $this->ajaxReturn(null, '无此用户', 201);
        }

        $res = db('user')->where('id', $userId)->update($post);
        if ($res!==false) {
            $this->ajaxReturn($res, 'ok', 200);
        }else{
            $this->ajaxReturn(null, '数据为空', 200);
        }
    }



    /**
     *
     *领红包
     * @return void
     */
    public function envelope()
    {
        $id = input('post.id');

        if (empty($id)) {
            $this->ajaxReturn(null, '参数错误', 201);
        }

        $share = db('share')->where('id', $id)->find();
        if(empty($share)){
            $this->ajaxReturn(null, '无分享数据', 201);
        }

        if($share['status']==2){
            $this->ajaxReturn(null, '已领取', 201);
        }

        $user = db('user')->where('id', $share['user_id'])->value('id');
        if(empty($user)){
            $this->ajaxReturn(null, '领取者身份验证失败', 201);
        }

        $spread = db('user')->where('id', $share['share_id'])->value('id');
        if(empty($spread)){
            $this->ajaxReturn(null, '分享者身份验证失败', 201);
        }

        $position = db('position')->where('id', $share['position_id'])->field('id,company_id')->find();
        if(empty($position)){
            $this->ajaxReturn(null, '无职位数据', 201);
        }
        $company = db('company')->where('id', $position['company_id'])->field('id,account,redbagmin,redbagmax')->find();
        if(empty($company)){
            $this->ajaxReturn(null, '无公司数据', 201);
        }

        if($company['account']<=0){
            $this->ajaxReturn(null, '无红包金额', 201);
        }

        if($company['redbagmin']<=0 || $company['redbagmax']<=0){
            $this->ajaxReturn(null, '未设置红包金额', 201);
        }

        $income = rand($company['redbagmin'], $company['redbagmax']);
        if($income>$company['account']){
            $income = $company['account'];
        }

        $data['share_id']   = $share['share_id'];
        $data['user_id']    = $share['user_id'];
        $data['position_id']= $position['id'];
        $data['company_id'] = $position['company_id'];
        $data['income']     = $income;
        $data['cdate']      = date('Y-m-d H:i:s');
        $data['ctime']      = time();
        $res = model('User')->envelope($share['type'], $data);
        if ($res!==false) {
            $this->ajaxReturn(['id'=>$res, 'income'=>$income], '领取成功', 200);
        }else{
            $this->ajaxReturn(null, '领取失败', 204);
        }
    }







    /**
     * 建议
     *
     * @return void
     */
    public function feedback()
    {
        $post = input('post.');
        if($post){
            $userId    = $post['user_id'];
            $content  = trim($post['content']);

            //验证token是否合法
            $user = db('user')->where('id', $userId)->field('id,nickName,avatarUrl')->find();
            if(empty($user)){
                $this->ajaxReturn(null, '身份验证失败', 201);
            }
            if(empty($content)){
                $this->ajaxReturn(null, '反馈内容不能为空', 202);
            }
            $content = !empty($content)?htmlspecialchars($content):'';

            $feedback['user_id']    = $userId;
            $feedback['nickName']   = $user['nickName'];
            $feedback['avatarUrl']  = $user['avatarUrl'];
            $feedback['content']    = $content;
            $feedback['ctime']      = time();
            $res = db('feedback')->insertGetId($feedback);
            if($res){
                $this->ajaxReturn(array('id'=>$res), 'OK', 200);
            }else{
                $this->ajaxReturn(null, '参数错误', 205);
            }

        }else{
            $this->ajaxReturn(null, '参数错误', 206);
        }
    }




    /**
     * 发送短信
     */
    public function sendcode()
    {
        require dirname(dirname(dirname(__DIR__))).'/vendor/shortmessage/autoload.php';
        $mobile = input('param.mobile');
        $type   = input('param.type');
        if(empty($type)){
            $this->ajaxReturn(null, '类型不能为空', 201);
        }

        if(empty($mobile)){
            $this->ajaxReturn(null, '电话为空', 201);
        }

        while(( $code = rand()%1000000)<100000);//生成四位随机整数验证码
        $smsOperator = new \SmsOperator();
        $data1['destMobiles'] = $mobile;
        $data1['content'] = '【校友会】您的验证码为：'.$code.'。如非本人操作，请忽略。';
        $result = $smsOperator->send_comSms($data1);
        if($result->responseData['respCode']==0){
            $data1['type']   = $type;
            $data1['code']   = $code;
            $data1['status'] = 1;
            $data1['ctime']  = time();
            $res = db('cms')->insertGetId($data1);
            $this->ajaxReturn($res, 'OK', 200);
        }else{
            $this->ajaxReturn($result->responseData['respCode'], $result->responseData['respMsg'], 204);
        }
    }


    /**
     * 提现
     *
     * @return void
     */
    public function withdraw()
    {
        $post = input('post.');
        $userId  = trim($post['user_id']);
        $amount  = intval($post['amount']);

        if(empty($userId)){
            $this->ajaxReturn(null, '身份验证不能为空', 201);
        }

        $user = db('user')->where('id', $userId)->field('id,wallet')->find();
        if(empty($user)){
            $this->ajaxReturn(null, '身份验证失败', 201);
        }

        if(empty($amount)){
            $this->ajaxReturn(null, '请填写提现金额', 202);
        }

        $income = db('income')->where('share_id', $user['id'])->sum('income');
        if(empty($income)){
            $this->ajaxReturn(null, '无推广收益', 202);
        }
        if($income < $user['wallet']){
            $this->ajaxReturn(null, '收益异常', 203);
        }
        if($amount > $user['wallet']){
            $this->ajaxReturn(null, '不能大于钱包收益', 205);
        }

        $order_sn = (intval(date('Y')) - 2010) . date('m') . date('d') . substr(time() , -5) . substr(microtime() , 2, 4);
        $order_sn = str_pad($order_sn, 12, rand(0, 9));


        $data['order_no']   = $order_sn;
        $data['user_id']    = $userId;
        $data['amount']     = $amount;  //提现金额
        $data['status']     = 1;
        $data['ctime']      = time();
        $res = db('withdraw')->insert($data);
        if($res!==false){
            db('user')->where('user_id', $userId)->setDec('wallet', $amount);
            $this->ajaxReturn($res, '申请成功', 200);
        }else{
            $this->ajaxReturn(null, '申请失败', 204);
        }
    }







    /**
     * 收益列表
     */
    public function income()
    {
        $userId = input('get.user_id');

        if(empty($userId)){
            $this->ajaxReturn(null, '身份验证不能为空', 201);
        }

        $user_id = db('user')->where('id', $userId)->value('id');
        if(empty($user_id)){
            $this->ajaxReturn(null, '身份验证失败', 201);
        }

        $list = db('income')->where(['share_id'=>$user_id])->order('id desc')->select();
        $ret = [];
        foreach($list as $key=>$val){
            $j = !empty($ret[$val['cdate']]['date'])?$ret[$val['cdate']]['date']:'';
            if($list[$key]['cdate'] == $j){
                $i = $i + $val['income'];
            }else{
                $i = $val['income'];
            }
            $ret[$val['cdate']]['date'] = $val['cdate'];
            $ret[$val['cdate']]['income'] = sprintf("%.2f", $i/100);
            $ret[$val['cdate']]['child'][] = $val;
        }

        if($ret){
            $ret = array_values($ret);
            $this->ajaxReturn($ret, 'ok', 200);
        }else{
            $this->ajaxReturn(null, '无数据', 200);
        }
    }



    /**
     * 充值金额
     *
     * @return void
     */
    public function rechargeAmount()
    {
        $ret = [
            [
                'value'=>1,
                'sort' =>1,
            ],
            [
                'value'=>10000,
                'sort' =>2,
            ],
            [
                'value'=>20000,
                'sort' =>3,
            ],
            [
                'value'=>50000,
                'sort' =>4,
            ]
        ];
        $this->ajaxReturn($ret, 'ok', 200);
    }


    /**
     * 提现记录
     */
    public function getwithdraw()
    {
        $userId = input('get.user_id');

        if(empty($userId)){
            $this->ajaxReturn(null, '身份验证不能为空', 201);
        }
        $userId = db('user')->where('id', $userId)->value('id');
        if(empty($userId)){
            $this->ajaxReturn(null, '无此用户', 201);
        }

        $where['user_id'] = $userId;
        $list =WithdrawalRecord::where($where)->order('id desc')->select();
        $ret = [];
        foreach($list as $key=>$val){
            $time =  date('Y-m-d', strtotime($val['create_time']));
            $j = !empty($ret[$time]['date'])?$ret[$time]['date']:'';
            $itemTime =  date('Y-m-d', strtotime($val['create_time']));
            if($itemTime == $j){
                $i = !empty($i)?$i:0;
                $i = $i + $val['amount'];
            }else{
                $i = $val['amount'];
            }
            $val['status'] = WithdrawalRecord::STATUS[ $val['status']];
            if ($val['admin_remark']) {
                $val['status'] .= ":".$val['admin_remark'];
            }
            $ret[$itemTime]['date'] = $itemTime;
            $ret[$itemTime]['amount'] = $i;
            $ret[$itemTime]['child'][] = $val;
        }

        if($ret){
            $ret = array_values($ret);
            $this->ajaxReturn($ret, 'ok', 200);
        }else{
            $this->ajaxReturn(null, '无数据', 200);
        }
    }


    # 反馈标签列表
    public function getfeedbacklist()
    {
        $tags = Feedbacktag::select();
        $this->ajaxReturn($tags, 'ok', 200);
    }


    # 注册协议
    public function regtext()
    {
        $text = Common::getRegText();
        return returnData(['regtext'=>$text]);
    }

    # 注册协议
    public function help()
    {
        $text = Common::getHelp();
        return returnData(['help'=>$text]);
    }

    public function getBgimg()
    {
        $data = Shareimg::order('sort','asc')->select();
        return returnData($data);
    }


    # 提现
    public function withdrawalCash(Request $request)
    {
        $data = $request::post();

        $validate = new \think\Validate($data, [
            'amount' => 'required',
            'real_name' => 'required',
            'type' => function($value,$data) {
                    if (in_array($value,['alipay','bank'])) {
                    }
                    return false;
            },
            'user_id' => 'required'
        ], [
            'real_name.required' => '真实姓名必填',
            'type' => '请选择 支付宝或 银行卡提现',
            'user_id' => '请选择 上传你的登录用户id',
        ]);
        if (!$validate->check($data)) {
            $errormsg = $validate->getError();
            return returnData([],$errormsg,'fail');
        }
        $user = \app\index\model\User::where('id', $data['user_id'])->find();
        if (!$user) {
            return returnData([],'用户不存在','fail');
        }
        if ($data['amount'] <= 0) {
            return returnData([],'金额不能为0或小于0','fail');
        }
        if ($data['amount']*100> $user->wallet) {
            return returnData([],'余额额不足','fail');
        }

        switch ($data['type'] ) {
            case 'bank':
            $validate = new \think\Validate($data,[
                'back_cardid' => 'required',
                'back_open_address' => 'required',
                'back_name' => 'required',
            ],[
                'back_cardid' => '卡号必须填',
                'back_open_address' => '开户行地址必须填',
                'back_name' => '开户所在银行名称必须填',
            ]);
            if (!$validate->check($data)) {
                $errormsg = $validate->getError();
                return returnData([],$errormsg,'fail');
            }
                $res = (new WithdrawalRecord())->bankWithdreawal(
                    $data['user_id'],
                    $data['amount'],
                    $data['real_name'],
                    $data['bank_name'],
                    $data['bank_cardid'],
                    $data['bank_open_address']
                );
                return returnData($res);
                break;
            case 'alipay':
                if (!isset($data['ali_account'])||!$data['ali_account']) {
                    return returnData([],'支付宝账户必须填','fail');
                }
                $res = (new WithdrawalRecord())->aliWithdrawal(
                    $data['user_id'],
                    $data['ali_account'],
                    $data['amount'],
                    $data['real_name']
                );
                return returnData($res);
                break;
            default:
                return returnData([],'未知提现方式','fail');
                break;
        }


    }
    public function withdrawalCashRecord(Request $request)
    {

    }


}
